package com.stormragetech.sylwanas.converter;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

import java.util.UUID;

/**
 * description: //TODO
 *
 * @author: Xue Bin
 * @version: 1.0.0-SNAPSHOT
 */
public class ProtobufMessageConverter implements MessageConverter {

    @Override
    public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {

        if (null == messageProperties) {
            messageProperties = new MessageProperties();
        }

        try {
            byte[] bytes = (byte[]) object;

            messageProperties.setContentType(MessageProperties.DEFAULT_CONTENT_TYPE);
            messageProperties.setContentLength((long) bytes.length);
            if (null == messageProperties.getMessageId()) {
                messageProperties.setMessageId(UUID.randomUUID().toString());
            }

            return new Message(bytes, messageProperties);

        } catch (Exception e) {
            throw new MessageConversionException("Failed to convert Message content", e);
        }
    }

    @Override
    public Object fromMessage(Message message) throws MessageConversionException {

        if (null == message.getMessageProperties().getContentType() || !MessageProperties.DEFAULT_CONTENT_TYPE.equals(message.getMessageProperties().getContentType())) {
            throw new MessageConversionException("Failed to convert Message content");
        }
        return message.getBody();
    }
}
